package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

/**
* @description: TODO
* @author 杨镇宇
* @date 2024/8/29 17:22
* @version 1.0
*/
@Component
@Slf4j
public class EsIndexUtils {

    private final RestHighLevelClient client;
    private final RequestOptions requestOptions;
    private final EsBConfig esBConfig;
    private final EsCConfig esCConfig;

    public EsIndexUtils(RestHighLevelClient client, RequestOptions requestOptions, EsBConfig esBConfig, EsCConfig esCConfig) {
        this.client = client;
        this.requestOptions = requestOptions;
        this.esBConfig = esBConfig;
        this.esCConfig = esCConfig;
    }
    /**
     * 查询es
     */
    public SearchResponse queryRequest(SearchRequest searchRequest ,String index){

        if (Stream.of("default","B","C").noneMatch(s -> s.equals(index))){
            log.error("请求中心错误，检查入参");
            throw  new RuntimeException("请求中心错误，检查入参");
        }
        try {
            if ("B".equals(index)) {
                RestHighLevelClient highLevelClient = esBConfig.getHighLevelClient();
                SearchResponse searchResponse = highLevelClient.search(searchRequest, esBConfig.getRequestOptions());
                releaseRestHighLevelClient(highLevelClient);
                return searchResponse;
            } else if ("C".equals(index)) {
                RestHighLevelClient highLevelClient = esCConfig.getHighLevelClient();
                SearchResponse searchResponse = highLevelClient.search(searchRequest, esCConfig.getRequestOptions());
                releaseRestHighLevelClient(highLevelClient);
                return searchResponse;
            } else {
                return client.search(searchRequest, requestOptions);

            }
        }catch (Exception e){
            log.error("查询es报错",e);

        }
        return null;

    }

    private void releaseRestHighLevelClient(RestHighLevelClient highLevelClient){
        try {
            highLevelClient.close();
        }catch (Exception e){
            log.error("es 关闭异常",e);
        }
    }
}
